﻿using System.Web.Mvc;
using NUnit.Framework;
using TeamsPortal.DataAccess;
using TeamsPortal.Tests.Fakes;
using TeamsPortal.Web.Controllers;
using TeamsPortal.Web.Controllers.Filters;
using TeamsPortal.Web.Routing;
using TeamsPortal.Web.State;

namespace TeamsPortal.Tests.Controllers
{
	[TestFixture]
	public class ActionFiltersTests
	{
		[Test]
		public void AuthorizationAttribute_Test()
		{
			var sessionItems = new System.Web.SessionState.SessionStateItemCollection();
			var controllerContext = new FakeControllerContext(new TopicsController(null, null, null, null), "http://localhost", null, null, new System.Collections.Specialized.NameValueCollection(), new System.Collections.Specialized.NameValueCollection(), new System.Web.HttpCookieCollection(), sessionItems);
			var context = new AuthorizationContext(controllerContext, new FakeActionDescriptor());
			var att = new RequireAuthorizationAttribute(UserRole.Member);
			att.Routes.Add(new StrictRoute("login", new MvcRouteHandler())
			{
				Url = "login",
				Defaults = new System.Web.Routing.RouteValueDictionary(new
				{
					controller = "Authentication",
					action = "Login"
				})
			});
			context.Result = null;
			att.OnAuthorization(context);
            Assert.IsInstanceOf<RedirectResult>(context.Result);

			//Test with user
			User user = ServicesTests.GetTestUser();
			sessionItems["User"] = new UserState(user, AuthenticationProvider.Facebook);
			context.Result = null;
			att.OnAuthorization(context);
			Assert.IsNull(context.Result);
		}

		[Test]
		public void ValidateReadAccessAttribute_Test()
		{
			var controller = new TopicsController(null, null, null, null);
			var controllerContext = new FakeControllerContext(controller, "http://localhost");
			var filterContext = new ActionExecutedContext(controllerContext, new FakeActionDescriptor(), false, null);
			var att = new ValidateReadAccessAttribute();

			filterContext.Result = new ViewResult();
			controller.ViewData.Model = new Topic();
			att.OnActionExecuted(filterContext);
			//The user should see the content
			Assert.IsTrue(filterContext.Result is ViewResult);

			filterContext.Result = new ViewResult();
			controller.ViewData.Model = new Topic() { ReadAccessRole = UserRole.Moderator};
			att.OnActionExecuted(filterContext);
			//The user should be redirected
			Assert.IsTrue(filterContext.Result is RedirectToRouteResult);
		}
	}
}
